<?php

# http://projects:8081/cdapp-2kt-api/api/seat_seeking_lastseen.php

include_once '_portal.php';

$content = isset($post->content) ? $post->content : null;

if ($content != null) {
  if (gettype($content) == 'array') {
    $output = [];
    foreach ($content as $user) {
      if ($user->codes && count($user->codes) > 0) {
        $output[] = seek($user->name, $user->codes);
      }
    }
    output($output);
  } elseif (gettype($content) == 'object') {
    if ($content->codes && count($content->codes) > 0) {
      output(seek($content->name, $content->codes));
    }
  } else {
    output(null);
  }
} else {
  output(null);
}

die();

function seek($name, $codes) {
  $lastseen = null;
  $details = [];
  foreach ($codes as $code) {
    $sql = "SELECT `startTime` FROM `2kt_seat_hours` WHERE `userName` = '{$name}' AND `sectorCodes` LIKE '%{$code}%' ORDER BY `startTime` DESC LIMIT 1";
    $result = exec_sql($sql);
    if ($result) {
      $details[] = [
        'code' => $code,
        'lastseen' => $result[0]['startTime'],
      ];
      if ($lastseen == null || strtotime($lastseen) < strtotime($result[0]['startTime'])) {
        $lastseen = $result[0]['startTime'];
      }
    } else {
      $details[] = [
        'code' => $code,
        'lastseen' => null,
      ];
    }
  }
  return ['user' => $name, 'lastseen' => $lastseen, 'details' => $details];
}